/**
 * @description 根据传入的时间，计算倒计时 （可根据传入服务器当前时间模拟计时）
 * @param {Date} currentDate 当前时间 (建议传入服务器当前时间，不传默认客户端当前时间)
 * @param {Date} finishInput 倒计时结束时间（必传）
 * @param {Function} callback 回调函数 （倒计时截止返回：Finished，倒计时中返回：‘xx天 xx小时 xx分 xx秒’）
 */
interface CountdownCallback {
	(message: string): void;
}

interface CountdownFunction {
	(currentDate: Date | string, finishInput: Date | string, callback: CountdownCallback): void;
}

const countdown: CountdownFunction = function (currentDate = new Date(), finishInput, callback) {
	if (!finishInput) {
		callback('Invalid time finishInput input');
		return;
	}
	const finishDate = !finishInput
		? new Date()
		: typeof finishInput === 'string'
			? new Date(finishInput)
			: finishInput instanceof Date
				? finishInput
				: new Date(finishInput);
	const startDate = !currentDate
		? new Date()
		: typeof currentDate === 'string'
			? new Date(currentDate)
			: currentDate instanceof Date
				? currentDate
				: new Date(currentDate);

	if (isNaN(finishDate.getTime()) || isNaN(startDate.getTime())) {
		callback('Invalid time input');
		return;
	}
	// 记录服务器时间差，用于后续计算
	let serverTime = startDate.getTime();
	const intervalId = setInterval(() => {
		serverTime += 1000; // 每次迭代增加1秒
		const timeLeft = finishDate.getTime() - serverTime;

		if (timeLeft <= 0) {
			clearInterval(intervalId);
			callback('Finished');
		} else {
			let output = '';

			const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
			const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

			if (days > 0) output += `${days} 天 `;
			if (hours > 0 || output) output += `${hours} 小时 `;
			if (minutes > 0 || output) output += `${minutes} 分 `;
			output += `${seconds} 秒`;

			callback(output.trim());
		}
	}, 1000);
};
export default countdown;
